<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生社交媒体数据增强分析仪表板</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // Chart.js 本地回退方案
        (function() {
            function loadLocalChart() {
                var s = document.createElement('script');
                s.src = '/static/js/chart.umd.min.js';
                s.onload = function() {
                    if (typeof window.Chart === 'undefined') {
                        var s2 = document.createElement('script');
                        s2.src = '/static/js/simple_chart.js';
                        document.head.appendChild(s2);
                    }
                };
                s.onerror = function() {
                    var s2 = document.createElement('script');
                    s2.src = '/static/js/simple_chart.js';
                    document.head.appendChild(s2);
                };
                document.head.appendChild(s);
            }
            window.addEventListener('load', function() {
                if (typeof window.Chart === 'undefined') {
                    loadLocalChart();
                }
            });
        })();
    </script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .dashboard-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            margin: 20px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }
        
        .metric-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin: 10px 0;
            text-align: center;
            transition: transform 0.3s ease;
        }
        
        .metric-card:hover {
            transform: translateY(-5px);
        }
        
        .metric-number {
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .section-title {
            color: #2c3e50;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        
        .nav-tabs .nav-link {
            color: #667eea;
            border: none;
            font-weight: bold;
        }
        
        .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
        }
        
        .model-performance {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
        }
        
        .cluster-card {
            border-left: 5px solid #667eea;
            background: #f8f9fa;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .image-gallery {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .image-card {
            background: white;
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .image-card img {
            width: 100%;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <h1 class="text-center mb-4">学生社交媒体数据增强分析仪表板</h1>
        <p class="text-center text-muted mb-5">基于机器学习和深度学习的综合分析平台</p>
        <div class="d-flex justify-content-center gap-2 mb-3">
            <button id="btnRun" class="btn btn-primary btn-sm">运行增强分析</button>
            <button id="btnReload" class="btn btn-outline-secondary btn-sm">重新加载本地结果</button>
        </div>
        <div class="chart-container" id="progressPanel" style="display:none">
            <h5>分析进度</h5>
            <div id="progressStatus" class="text-muted">准备中...</div>
            <pre id="progressLog" style="max-height:200px; overflow:auto; background:#f8f9fa; padding:10px; border-radius:8px;"></pre>
        </div>
        
        <!-- 导航标签 -->
        <ul class="nav nav-tabs mb-4" id="dashboardTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button">概览</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="ml-tab" data-bs-toggle="tab" data-bs-target="#ml" type="button">机器学习</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="dl-tab" data-bs-toggle="tab" data-bs-target="#dl" type="button">深度学习</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="clustering-tab" data-bs-toggle="tab" data-bs-target="#clustering" type="button">聚类分析</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="visualizations-tab" data-bs-toggle="tab" data-bs-target="#visualizations" type="button">可视化</button>
            </li>
        </ul>
        
        <!-- 标签内容 -->
        <div class="tab-content" id="dashboardTabContent">
            <!-- 概览标签 -->
            <div class="tab-pane fade show active" id="overview" role="tabpanel">
                <h2 class="section-title">📊 数据概览</h2>
                
                <!-- 关键指标卡片 -->
                <div class="row" id="overviewMetrics">
                    <div class="col-md-3">
                        <div class="metric-card">
                            <div class="metric-number" id="totalSamples">-</div>
                            <div>总样本数</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="metric-card">
                            <div class="metric-number" id="avgUsage">-</div>
                            <div>平均使用时长(小时)</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="metric-card">
                            <div class="metric-number" id="avgMentalHealth">-</div>
                            <div>平均心理健康评分</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="metric-card">
                            <div class="metric-number" id="academicImpact">-</div>
                            <div>学术影响比例(%)</div>
                        </div>
                    </div>
                </div>
                
                <!-- 平台分析 -->
                <div class="chart-container">
                    <h3>平台使用分析</h3>
                    <div id="platformAnalysis" class="loading">加载中...</div>
                </div>
            </div>
            
            <!-- 机器学习标签 -->
            <div class="tab-pane fade" id="ml" role="tabpanel">
                <h2 class="section-title">🤖 机器学习分析</h2>
                
                <div class="row" id="mlResults">
                    <div class="loading">加载中...</div>
                </div>
                
                <div class="chart-container">
                    <h3>特征重要性</h3>
                    <canvas id="featureImportanceChart"></canvas>
                </div>
            </div>
            
            <!-- 深度学习标签 -->
            <div class="tab-pane fade" id="dl" role="tabpanel">
                <h2 class="section-title">🧠 深度学习分析</h2>
                
                <div id="dlResults" class="loading">加载中...</div>
                
                <div class="chart-container">
                    <h3>训练历史</h3>
                    <canvas id="trainingHistoryChart"></canvas>
                </div>
            </div>
            
            <!-- 聚类分析标签 -->
            <div class="tab-pane fade" id="clustering" role="tabpanel">
                <h2 class="section-title">🎯 聚类分析</h2>
                
                <div id="clusteringResults" class="loading">加载中...</div>
            </div>
            
            <!-- 可视化标签 -->
            <div class="tab-pane fade" id="visualizations" role="tabpanel">
                <h2 class="section-title">📈 高级可视化</h2>
                
                <div class="image-gallery">
                    <div class="image-card">
                        <h4>使用时间分布</h4>
                        <img src="/charts/usage_distribution.png" alt="使用时间分布" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>平台分布</h4>
                        <img src="/charts/platform_distribution.png" alt="平台分布" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>心理健康分析</h4>
                        <img src="/charts/mental_health_analysis.png" alt="心理健康分析" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>学术影响分析</h4>
                        <img src="/charts/academic_impact.png" alt="学术影响分析" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>人口统计分析</h4>
                        <img src="/charts/demographics.png" alt="人口统计分析" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>平台成瘾分析</h4>
                        <img src="/charts/platform_addiction.png" alt="平台成瘾分析" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>特征重要性</h4>
                        <img src="/charts/feature_importance.png" alt="特征重要性" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>国家对比</h4>
                        <img src="/charts/country_comparison.png" alt="国家对比" onerror="this.style.display='none'">
                    </div>
                    <div class="image-card">
                        <h4>聚类可视化</h4>
                        <img src="/charts/clustering_visualization.png" alt="聚类可视化" onerror="this.style.display='none'">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadOverviewData();
            loadMachineLearningData();
            loadDeepLearningData();
            loadClusteringData();

            // 绑定按钮
            document.getElementById('btnRun').addEventListener('click', startAnalysisRun);
            document.getElementById('btnReload').addEventListener('click', reloadResults);
            // 首次加载尝试显示历史进度
            pollProgress(true);
        });
        
        // 加载概览数据
        async function loadOverviewData() {
            try {
                const response = await fetch('/api/basic_stats');
                const data = await response.json();
                
                if (data.total_students) {
                    document.getElementById('totalSamples').textContent = data.total_students.toLocaleString();
                    document.getElementById('avgUsage').textContent = data.avg_daily_usage.toFixed(1);
                    document.getElementById('avgMentalHealth').textContent = data.avg_mental_health.toFixed(1);
                    document.getElementById('academicImpact').textContent = data.academic_affected_percentage.toFixed(1);
                }
                
                // 加载平台分析
                const platformResponse = await fetch('/api/platform_analysis');
                const platformData = await platformResponse.json();
                
                if (platformData && Object.keys(platformData).length > 0) {
                    displayPlatformAnalysis(platformData);
                } else {
                    document.getElementById('platformAnalysis').innerHTML = '<span class="text-muted">暂无平台分析数据</span>';
                }
                
            } catch (error) {
                console.error('加载概览数据失败:', error);
            }
        }

        // 触发后台分析
        async function startAnalysisRun() {
            try {
                document.getElementById('progressPanel').style.display = '';
                document.getElementById('progressStatus').textContent = '启动中...';
                document.getElementById('progressLog').textContent = '';
                const resp = await fetch('/api/run_analysis', { method: 'POST' });
                const data = await resp.json();
                if (resp.ok) {
                    document.getElementById('progressStatus').textContent = data.status === 'running' ? '分析已在运行' : '已启动分析';
                    pollProgress();
                } else {
                    document.getElementById('progressStatus').textContent = '启动失败';
                }
            } catch(e) {
                console.error(e);
            }
        }

        // 轮询进度
        let progressTimer = null;
        async function pollProgress(initial=false) {
            try {
                const resp = await fetch('/api/progress');
                const data = await resp.json();
                const panel = document.getElementById('progressPanel');
                const log = document.getElementById('progressLog');
                const status = document.getElementById('progressStatus');
                if (initial && (!data.messages || data.messages.length === 0)) return;
                panel.style.display = '';
                status.textContent = data.running ? '正在分析...' : '空闲';
                log.textContent = (data.messages || []).join('\n');
                if (data.running && !progressTimer) {
                    progressTimer = setInterval(pollProgress, 1500);
                }
                if (!data.running && progressTimer) {
                    clearInterval(progressTimer);
                    progressTimer = null;
                    // 结束后刷新数据区域
                    loadOverviewData();
                    loadMachineLearningData();
                    loadDeepLearningData();
                    loadClusteringData();
                }
            } catch(e) {
                console.error(e);
            }
        }

        async function reloadResults() {
            try {
                const resp = await fetch('/api/reload', { method: 'POST' });
                await resp.json();
                loadOverviewData();
                loadMachineLearningData();
                loadDeepLearningData();
                loadClusteringData();
            } catch(e) {}
        }
        
        // 显示平台分析
        function displayPlatformAnalysis(data) {
            const container = document.getElementById('platformAnalysis');
            let html = '<div class="row">';
            
            Object.entries(data).forEach(([platform, stats]) => {
                html += `
                    <div class="col-md-4 mb-3">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">${platform}</h5>
                                <p class="card-text">
                                    用户数量: ${stats['用户数量']}<br>
                                    平均使用时长: ${stats['平均使用时长']} 小时<br>
                                    平均心理健康: ${stats['平均心理健康']}<br>
                                    平均成瘾评分: ${stats['平均成瘾评分']}<br>
                                    学术影响比例: ${stats['学术影响比例(%)']}%
                                </p>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            container.innerHTML = html;
        }
        
        // 加载机器学习数据
        async function loadMachineLearningData() {
            try {
                const response = await fetch('/api/machine_learning');
                const data = await response.json();
                
                if (Object.keys(data).length > 0) {
                    displayMachineLearningResults(data);
                }
                
                // 加载特征重要性
                const featureResponse = await fetch('/api/feature_importance');
                const featureData = await featureResponse.json();
                
                if (featureData.length > 0) {
                    displayFeatureImportance(featureData);
                }
                
            } catch (error) {
                console.error('加载机器学习数据失败:', error);
            }
        }
        
        // 显示机器学习结果
        function displayMachineLearningResults(data) {
            const container = document.getElementById('mlResults');
            let html = '';
            
            Object.entries(data).forEach(([modelName, results]) => {
                html += `
                    <div class="col-md-6 mb-3">
                        <div class="model-performance">
                            <h4>${modelName}</h4>
                            <p>准确率: <strong>${(results.accuracy * 100).toFixed(1)}%</strong></p>
                            <p>AUC: <strong>${results.auc.toFixed(3)}</strong></p>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // 显示特征重要性
        function displayFeatureImportance(data) {
            if (!data || data.length === 0) {
                const parent = document.getElementById('featureImportanceChart').parentElement;
                parent.innerHTML = '<p class="text-muted">暂无特征重要性数据</p>';
                return;
            }
            const ctx = document.getElementById('featureImportanceChart').getContext('2d');
            
            const chart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.map(item => item.feature),
                    datasets: [{
                        label: '重要性',
                        data: data.map(item => item.importance),
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 加载深度学习数据
        async function loadDeepLearningData() {
            try {
                const response = await fetch('/api/deep_learning');
                const data = await response.json();
                
                if (data && Object.keys(data).length > 0) {
                    displayDeepLearningResults(data);
                } else {
                    document.getElementById('dlResults').innerHTML = '<p class="text-muted">暂无深度学习数据</p>';
                }
                
            } catch (error) {
                console.error('加载深度学习数据失败:', error);
                document.getElementById('dlResults').innerHTML = '<p class="text-muted">深度学习分析不可用（TensorFlow未安装）</p>';
            }
        }
        
        // 显示深度学习结果
        function displayDeepLearningResults(data) {
            const container = document.getElementById('dlResults');
            
            const html = `
                <div class="model-performance">
                    <h4>深度学习模型性能</h4>
                    <div class="row">
                        <div class="col-md-4">
                            <p>测试准确率: <strong>${(data.test_accuracy * 100).toFixed(1)}%</strong></p>
                        </div>
                        <div class="col-md-4">
                            <p>AUC: <strong>${data.auc.toFixed(3)}</strong></p>
                        </div>
                        <div class="col-md-4">
                            <p>测试损失: <strong>${data.test_loss.toFixed(3)}</strong></p>
                        </div>
                    </div>
                </div>
            `;
            
            container.innerHTML = html;
            
            // 显示训练历史
            if (data.training_history) {
                displayTrainingHistory(data.training_history);
            }
        }
        
        // 显示训练历史
        function displayTrainingHistory(history) {
            const ctx = document.getElementById('trainingHistoryChart').getContext('2d');
            
            const chart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: history.loss.map((_, i) => i + 1),
                    datasets: [{
                        label: '训练损失',
                        data: history.loss,
                        borderColor: 'rgba(255, 99, 132, 1)',
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        tension: 0.1
                    }, {
                        label: '验证损失',
                        data: history.val_loss,
                        borderColor: 'rgba(54, 162, 235, 1)',
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // 加载聚类数据
        async function loadClusteringData() {
            try {
                const response = await fetch('/api/clustering');
                const data = await response.json();
                
                if (data && Object.keys(data).length > 0) {
                    displayClusteringResults(data);
                } else {
                    document.getElementById('clusteringResults').innerHTML = '<span class="text-muted">暂无聚类分析数据</span>';
                }
                
            } catch (error) {
                console.error('加载聚类数据失败:', error);
                document.getElementById('clusteringResults').innerHTML = '<span class="text-muted">加载聚类数据失败</span>';
            }
        }
        
        // 显示聚类结果
        function displayClusteringResults(data) {
            const container = document.getElementById('clusteringResults');
            
            if (data.cluster_stats && data.cluster_descriptions) {
                let html = '<div class="row">';
                
                Object.entries(data.cluster_stats).forEach(([clusterId, stats]) => {
                    const description = data.cluster_descriptions[clusterId] || `聚类${clusterId}`;
                    
                    html += `
                        <div class="col-md-6 mb-3">
                            <div class="cluster-card">
                                <h4>聚类 ${clusterId} - ${description}</h4>
                                <p>用户数量: ${stats['人数']}</p>
                                <p>平均年龄: ${stats['平均年龄']} 岁</p>
                                <p>平均使用时长: ${stats['平均使用时长']} 小时</p>
                                <p>平均心理健康: ${stats['平均心理健康']}</p>
                                <p>平均成瘾评分: ${stats['平均成瘾评分']}</p>
                            </div>
                        </div>
                    `;
                });
                
                html += '</div>';
                container.innerHTML = html;
            }
        }
    </script>
</body>
</html>